package io.kiki.stack.http.feign.SpringMvcContract.annotation;

import io.kiki.stack.http.feign.MethodMetadata;
import io.kiki.stack.http.feign.SpringMvcContract.AnnotatedParameterProcessor;
import org.springframework.web.bind.annotation.RequestPart;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;

import static io.kiki.stack.http.feign.Util.checkState;
import static io.kiki.stack.http.feign.Util.emptyToNull;

/**
 * {@link RequestPart} parameter processor.
 */
public class RequestPartParameterProcessor implements AnnotatedParameterProcessor {

    private static final Class<RequestPart> ANNOTATION = RequestPart.class;

    @Override
    public Class<? extends Annotation> getAnnotationType() {
        return ANNOTATION;
    }

    @Override
    public boolean processArgument(AnnotatedParameterContext annotatedParameterContext, Annotation annotation, Method method) {
        int parameterIndex = annotatedParameterContext.getParameterIndex();
        MethodMetadata data = annotatedParameterContext.getMethodMetadata();

        String name = ANNOTATION.cast(annotation).value();
        checkState(emptyToNull(name) != null, "RequestPart.value() was empty on parameter %s", parameterIndex);
        annotatedParameterContext.setParameterName(name);

        data.formParams().add(name);
        Collection<String> names = annotatedParameterContext.setTemplateParameter(name, data.indexToName().get(parameterIndex));
        data.indexToName().put(parameterIndex, names);
        return true;
    }

}
